const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
const querystring = require('querystring');

// 确保upload目录存在
const uploadDir = path.join(__dirname, 'upload');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 创建HTTP服务器
const server = http.createServer((req, res) => {
  const parsedUrl = url.parse(req.url, true);
  const pathname = parsedUrl.pathname;

  // 处理根路径 - 显示上传表单
  if (pathname === '/' && req.method === 'GET') {
    const html = `
      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="UTF-8">
        <title>图片管理器</title>
        <style>
          body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
          .container { text-align: center; }
          .upload-form { margin: 20px 0; padding: 20px; border: 1px solid #ccc; border-radius: 5px; }
          input[type="file"] { margin: 10px 0; }
          button { padding: 8px 16px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; }
          button:hover { background-color: #45a049; }
          .image-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; margin-top: 20px; }
          .image-item { border: 1px solid #ddd; padding: 10px; border-radius: 5px; }
          .image-item img { max-width: 100%; max-height: 150px; object-fit: contain; }
          a { color: #007bff; text-decoration: none; }
          a:hover { text-decoration: underline; }
        </style>
      </head>
      <body>
        <div class="container">
          <h1>图片管理器</h1>
          <div class="upload-form">
            <h2>上传新图片</h2>
            <form action="/upload" method="POST" enctype="multipart/form-data">
              <input type="file" name="image" accept="image/*" required>
              <br>
              <button type="submit">提交</button>
            </form>
          </div>
          <p>查看所有图片: <a href="/list">图片列表</a></p>
        </div>
      </body>
      </html>
    `;
    
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(html);
  }

  // 处理图片上传
  else if (pathname === '/upload' && req.method === 'POST') {
    let body = '';
    let boundary = req.headers['content-type'].split('; ')[1].split('=')[1];
    let fileName = null;
    let fileData = [];
    let isFilePart = false;

    req.on('data', (chunk) => {
      body += chunk.toString('binary');
      
      // 查找文件名
      if (!fileName) {
        const match = chunk.toString().match(/filename="(.*?)"/);
        if (match && match[1]) {
          fileName = match[1];
          isFilePart = true;
        }
      }
      // 收集文件数据
      else if (isFilePart) {
        // 检查是否到达文件部分的末尾
        if (chunk.toString().includes(`--${boundary}--`)) {
          isFilePart = false;
          // 只取到边界前的数据
          const endIndex = chunk.indexOf(`--${boundary}--`);
          if (endIndex > 0) {
            fileData.push(chunk.slice(0, endIndex));
          }
        } else {
          fileData.push(chunk);
        }
      }
    });

    req.on('end', () => {
      if (!fileName) {
        res.writeHead(400, { 'Content-Type': 'text/plain' });
        res.end('未选择图片');
        return;
      }

      // 确保文件名唯一
      const ext = path.extname(fileName);
      const baseName = path.basename(fileName, ext);
      let uniqueFileName = `${baseName}${ext}`;
      let counter = 1;
      
      while (fs.existsSync(path.join(uploadDir, uniqueFileName))) {
        uniqueFileName = `${baseName}_${counter}${ext}`;
        counter++;
      }

      // 合并文件数据并去除头部信息
      const fileBuffer = Buffer.concat(fileData);
      const headerEndIndex = fileBuffer.indexOf('\r\n\r\n') + 4;
      const cleanFileBuffer = fileBuffer.slice(headerEndIndex);

      // 保存文件
      const filePath = path.join(uploadDir, uniqueFileName);
      fs.writeFile(filePath, cleanFileBuffer, (err) => {
        if (err) {
          res.writeHead(500, { 'Content-Type': 'text/plain' });
          res.end('上传失败: ' + err.message);
        } else {
          res.writeHead(200, { 'Content-Type': 'text/html' });
          res.end(`
            <!DOCTYPE html>
            <html>
            <head>
            <meta charset="UTF-8">
              <title>上传成功</title>
              <style>
                body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
                a { color: #007bff; text-decoration: none; }
              </style>
            </head>
            <body>
              <h1>图片上传成功!</h1>
              <p>文件名: ${uniqueFileName}</p>
              <p><a href="/">返回首页</a> | <a href="/list">查看所有图片</a></p>
            </body>
            </html>
          `);
        }
      });
    });
  }

  // 处理图片列表请求
  else if (pathname === '/list' && req.method === 'GET') {
    fs.readdir(uploadDir, (err, files) => {
      if (err) {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('无法读取图片目录: ' + err.message);
        return;
      }

      // 过滤出图片文件
      const imageFiles = files.filter(file => {
        const ext = path.extname(file).toLowerCase();
        return ['.jpg', '.jpeg', '.png', '.gif', '.bmp'].includes(ext);
      });

      // 生成图片列表HTML
      let imagesHtml = '';
      if (imageFiles.length === 0) {
        imagesHtml = '<p>暂无图片</p>';
      } else {
        imageFiles.forEach(file => {
          imagesHtml += `
            <div class="image-item">
              <img src="/images/${file}" alt="${file}">
              <p>${file}</p>
            </div>
          `;
        });
      }

      const html = `
        <!DOCTYPE html>
        <html>
        <head>
        <meta charset="UTF-8">
          <title>图片列表</title>
          <style>
            body { font-family: Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; }
            .container { text-align: center; }
            .image-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; margin-top: 20px; }
            .image-item { border: 1px solid #ddd; padding: 10px; border-radius: 5px; }
            .image-item img { max-width: 100%; max-height: 150px; object-fit: contain; }
            a { color: #007bff; text-decoration: none; }
            a:hover { text-decoration: underline; }
          </style>
        </head>
        <body>
          <div class="container">
            <h1>图片列表</h1>
            <p>共有 ${imageFiles.length} 张图片</p>
            <div class="image-list">
              ${imagesHtml}
            </div>
            <p style="margin-top: 20px;"><a href="/">返回首页上传新图片</a></p>
          </div>
        </body>
        </html>
      `;

      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(html);
    });
  }

  // 处理图片请求
  else if (pathname.startsWith('/images/') && req.method === 'GET') {
    const fileName = path.basename(pathname);
    const filePath = path.join(uploadDir, fileName);

    fs.readFile(filePath, (err, data) => {
      if (err) {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('图片不存在');
        return;
      }

      // 设置正确的Content-Type
      const ext = path.extname(fileName).toLowerCase();
      let contentType = 'image/jpeg';
      if (ext === '.png') contentType = 'image/png';
      else if (ext === '.gif') contentType = 'image/gif';
      else if (ext === '.bmp') contentType = 'image/bmp';

      res.writeHead(200, { 'Content-Type': contentType });
      res.end(data);
    });
  }

  // 处理404
  else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('页面未找到');
  }
});

// 启动服务器
const PORT = 8082;
server.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
  console.log(`- 访问 http://localhost:${PORT} 上传图片`);
  console.log(`- 访问 http://localhost:${PORT}/list 查看所有图片`);
});
